package org.wxd.ms.stu.aggre.web;

import com.google.common.collect.Maps;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.wxd.ms.stu.aggre.domain.User;
import org.wxd.ms.stu.aggre.service.UserAggreService;
import rx.Observable;
import rx.Observer;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * Created by wangxd on 2017/6/12.
 */
@RestController
public class AggreCTL {

    @Resource
    private UserAggreService aggreService;

    @GetMapping("/aggre/{id}")
    public DeferredResult<HashMap<String,User>> aggregate(@PathVariable("id") Long id){
        Observable<HashMap<String,User>> result = this.aggregateObservable(id);
        return this.toDeferredResult(result);
    }

    public Observable<HashMap<String,User>> aggregateObservable(Long id){
        return Observable.zip(
                this.aggreService.getUserById(id),
                this.aggreService.getUser(id + 1),
                (user,user2) -> {
                    HashMap<String,User> map = Maps.newHashMap();
                    map.put(id + "",user);
                    map.put((id + 1) + "",user2);
                    return map;
                }
        );
    }
    public DeferredResult<HashMap<String,User>> toDeferredResult(Observable<HashMap<String,User>> details){
        DeferredResult<HashMap<String,User>> result = new DeferredResult<>();

        details.subscribe(new Observer<HashMap<String, User>>() {
            @Override
            public void onCompleted() {
                System.out.println("done.");
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void onNext(HashMap<String, User> stringUserHashMap) {
                result.setResult(stringUserHashMap);
            }
        });

        return result;
    }

}
